//
//  Radiogroup.m
//  CarTown
//
//  Created by xionghao on 15/8/9.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "Radiogroup.h"
#import "XHRadiobutton.h"
@implementation Radiogroup

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(void)setSelectedIndex:(NSInteger)selectedIndex{
    _selectedIndex=selectedIndex;
    
    for (int i=0;i<self.subviews.count;i++) {
        XHRadiobutton *btn=self.subviews[i];
       
        if (btn.isSelected&&btn.tag==_selectedIndex) {
            btn.selected=NO;
            if (!self.isnotcancel) {
                 _selectedIndex=-1;
            }
        }else{
            btn.selected=NO;
        }
   }
    if (_selectedIndex==-1) {
        return;
    }
  XHRadiobutton *btn= self.subviews[_selectedIndex];
    btn.selected=YES;
    
}

-(void)setTitlesarray:(NSArray *)titlesarray{
    
    _titlesarray=titlesarray;
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    CGFloat y;
    CGFloat height=24;
    CGFloat width;
    UIFont *font;
    if (XHScreenwidth==320) {
      
        font=[UIFont systemFontOfSize:12];
    }else{
       
         font=[UIFont systemFontOfSize:14];
    }
    
    CGFloat x=0;
    CGFloat lastwidth=0;
    if (self.height>24) {
        y=(self.height-24)/2;
    }else{
        y=0;
    }
    for (int i=0; i<titlesarray.count; i++) {
        XHRadiobutton *button=[[XHRadiobutton alloc] init];
        [button setTitle:titlesarray[i] forState:UIControlStateNormal];
           CGSize size =[titlesarray[i] sizeWithAttributes:@{NSFontAttributeName:font}];
        
        button.titleLabel.font=font;
        [button setBackgroundImage:[UIImage imageWithStretchableName:@"normal_boder"] forState:UIControlStateNormal];
        button.tag=i;
        [button setTitleColor:UIColorWithRGB(165, 165, 165) forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithStretchableName:@"blue_boder"] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(checked:) forControlEvents:UIControlEventTouchUpInside];
        
        if (size.width+4>(XHScreenwidth==320?36:48)) {
            width=size.width+4;
        }else{
            width=XHScreenwidth==320?36:48;
        }
        x+=lastwidth+10;
        lastwidth=width;
        button.frame=CGRectMake(x, y, width, height);
        
        [self addSubview: button];
    }
}


-(void)checked:(XHRadiobutton *)button{
    
    self.selectedValue=button.titleLabel.text;
    self.selectedIndex=button.tag;
    if ([_delegate respondsToSelector:@selector(RadiobuttonSelect:withValue:)]) {
        [_delegate RadiobuttonSelect:self.selectedIndex withValue:self.selectedValue];
    }
}

@end
